package com.rzico.sbl.ui.goods

import com.google.android.flexbox.*
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityGoodsEditBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.model.GoodsTagData
import com.rzico.sbl.viewmodel.GoodsViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common.other.NameLengthFilter
import com.xinnuo.common.view.AutoResizeTextView
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject
import kotlin.text.orEmpty

class GoodsEditActivity : BaseActivity(R.layout.activity_goods_edit) {

    private val mBinding by lazy { ActivityGoodsEditBinding.bind(getRootView()) }

    private val mKindList = ArrayList<CommonData>()
    private val mBrandList = ArrayList<CommonData>()
    private val mTagList = ArrayList<GoodsTagData>()

    private var mKindId = ""  //商品分类Id
    private var mType = ""    //商品类型
    private var mBrandId = "" //商品品牌Id

    override fun getViewModel() = get<GoodsViewModel>()

    override fun initData() {
        initTitle(title = "商品编辑", name = "删除")

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding
            .goodsTag
            .apply {
                isNestedScrollingEnabled = false
                layoutManager = FlexboxLayoutManager(
                    getIContext(),
                    FlexDirection.ROW,
                    FlexWrap.WRAP
                ).apply {
                    justifyContent = JustifyContent.FLEX_START
                    alignItems = AlignItems.FLEX_START
                }

                addItemDecoration(
                    FlexboxItemDecoration(getIContext()).apply {
                        setDrawable(getDrawableEx(R.drawable.rect_tag_flex_space))
                    }
                )

                adapter = SlimAdapter.creator()
                    .register<GoodsTagData>(R.layout.item_goods_tag_flex) { jector, bean, _ ->
                        jector.apply {
                            with<AutoResizeTextView>(R.id.item_goods_tag) {
                                it.setMinTextSize(8f)
                                it.text = bean.name

                                it.setBackgroundResource(
                                    conditionIf(
                                        bean.isChecked,
                                        R.mipmap.icon_goods03,
                                        R.drawable.rec_bg_trans_stroke_light_r5
                                    )
                                )

                                it.setTextColor(
                                    getColorEx(
                                        conditionIf(
                                            bean.isChecked,
                                            R.color.colorAccent,
                                            R.color.gray
                                        )
                                    )
                                )
                            }

                            clicked {
                                bean.isChecked = !bean.isChecked
                                notifyDataSetChanged()
                            }
                        }
                    }
                    .attachTo(this)
            }

        tvRight?.oneClick {
            showHintDialog(
                title = "删除商品",
                hint = "确定要删除商品吗？",
                sure = "删除",
                onSure = {
                    getViewModel()
                        .productDel(intent.getExtra("itemId"))
                        .bindLifeCycle(getLifecycleOwner())
                        .subscribeBySuccess(
                            event = getViewModel(),
                            onSuccess = {
                                showToast("商品删除成功！")

                                intent
                                    .getIntExtra("index", -1)
                                    .also {
                                        // 更新商品列表
                                        LiveEventBus
                                            .get("productList")
                                            .post("delete,$it")
                                    }

                                finishView()
                            }
                        )
                }
            )
        }
    }

    override fun initListener() {
        mBinding.apply {
            goodsMarket.filters = arrayOf(DecimalNumberFilter(), NameLengthFilter(8))
            goodsPrice.filters = arrayOf(DecimalNumberFilter(), NameLengthFilter(8))
            goodsCost.filters = arrayOf(DecimalNumberFilter(), NameLengthFilter(8))

            goodsFenLl.oneClick {
                mKindList.isEmpty()
                    .conditionElse(
                        actionTrue = { getKindList { showKindDialog() } },
                        actionFalse = ::showKindDialog
                    )
            }

            goodsShangLl.oneClick {
                showListDialog(
                    title = "请选择类型",
                    index = when (mType) {
                        "product" -> 0
                        "water" -> 1
                        "dummy" -> 2
                        "gift" -> 3
                        else -> -1
                    },
                    items = listOf("普通商品", "同城特供", "虚拟商品", "赠品"),
                    listener = { index, hint ->
                        when (index) {
                            0 -> mType = "product"
                            1 -> mType = "water"
                            2 -> mType = "dummy"
                            3 -> mType = "gift"
                        }
                        goodsShang.text = hint
                    }
                )
            }

            goodsPinLl.oneClick {
                mBrandList.isEmpty()
                    .conditionElse(
                        actionTrue = { getBrandList { showBrandDialog() } },
                        actionFalse = ::showBrandDialog
                    )
            }

            goodsPinArrow.oneClick {
                mBrandId.notEmpty {
                    mBrandId = ""
                    goodsPin.text = ""

                    goodsPinArrow
                        .apply {
                            layoutParams.apply {
                                width = dp2px(13f)
                                height = dp2px(13f)
                            }
                            setImageResource(R.mipmap.icon_arrow)
                        }
                }
            }

            btSave.oneClick {
                when {
                    goodsPrice.text.isEmpty() -> {
                        goodsPrice.requestFocus()
                        showToast("请输入销售价格")
                        return@oneClick
                    }
                    goodsStock.text.isEmpty() -> {
                        goodsStock.requestFocus()
                        showToast("请输入库存数")
                        return@oneClick
                    }
                    goodsPrice.textDouble <= 0 -> {
                        showToast("销售价不能低于0")
                        return@oneClick
                    }
                }

                getViewModel()
                    .productSub(
                        "id" to intent.getExtra("itemId"),
                        "price" to goodsPrice.content,
                        "marketPrice" to goodsMarket.content,
                        "cost" to goodsCost.content,
                        "stock" to goodsStock.content,
                        "monthSale" to goodsMonth.content,
                        "spec1" to goodsSpec.textTrim,
                        "spec2" to goodsColor.textTrim,
                        "productCategoryId" to mKindId,
                        "type" to mType,
                        "barrelId" to mBrandId,
                        "tagIds" to mTagList.filter { it.isChecked }.joinToString(",") { it.id }
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("信息保存成功！")

                            // 更新商品列表
                            LiveEventBus
                                .get("productList")
                                .post("refresh")

                            finishView()
                        }
                    )
            }
        }
    }

    private fun showKindDialog() {
        showListDialog(
            title = "请选择分类",
            index = mKindList.indexOfFirst { it.id == mKindId },
            items = mKindList.map { it.name.orEmpty() },
            listener = { index, hint ->
                mKindId = mKindList[index].id
                mBinding.goodsFen.text = hint
            }
        )
    }

    private fun showBrandDialog() {
        showListDialog(
            title = "请选择品牌",
            index = mBrandList.indexOfFirst { it.id == mBrandId },
            items = mBrandList.map { it.name.orEmpty() },
            listener = { index, hint ->
                mBrandId = mBrandList[index].id
                mBinding.goodsPin.text = hint

                mBinding
                    .goodsPinArrow
                    .apply {
                        layoutParams.apply {
                            width = dp2px(15f)
                            height = dp2px(15f)
                        }
                        setImageResource(R.mipmap.icon_arrow_close)
                    }
            }
        )
    }

    /**
     * 分类列表
     */
    private fun getKindList(onFinish: () -> Unit) {
        getViewModel()
            .productCat()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mKindList.addItems(it)
                    onFinish.invoke()
                }
            )
    }

    /**
     * 品牌列表
     */
    private fun getBrandList(onFinish: () -> Unit) {
        getViewModel()
            .requestCommon(
                isLoading = true,
                requestUrl = BaseUrl.bucketPdt,
                requestMethod = HttpMethod.GET,
                onSuccess = {
                    mBrandList.addItems(it)
                    onFinish.invoke()
                }
            )
    }

    /**
     * 商品标签
     */
    private fun productTag(onNext: () -> Unit) {
        getViewModel()
            .productTag()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mTagList.clear()
                    mTagList.addItems(it)

                    onNext.invoke()
                }
            )
    }

    /**
     * 商品详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .productInfo(intent.getExtra("itemId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mBinding.apply {
                        goodsName.text = obj.optNotNull("name")
                        goodsUnit.text = obj.optNotNull("unit")

                        obj.optNotNull("stock")
                            .also {
                                (it.intValue > 0).condition {
                                    goodsStock.setText(it)
                                }
                            }

                        obj.optNotNull("monthSale")
                            .also {
                                (it.intValue > 0).condition {
                                    goodsMonth.setText(it)
                                }
                            }

                        goodsShang.text =
                            when (obj.optNotNull("type")
                                .also { mType = it }
                            ) {
                                "product" -> "普通商品"
                                "water" -> "同城特供"
                                "dummy" -> "虚拟商品"
                                "gift" -> "赠品"
                                else -> ""
                            }
                    }

                    // 商品分类
                    val objKind = obj.optJSONObject("productCategory")
                    mKindId = objKind.optNotNull("id")
                    mBinding.goodsFen.text = objKind.optNotNull("name")

                    // 商品品牌
                    val objBrand = obj.optJSONObject("barrel")
                    objBrand.optNotNull("id")
                        .notEmpty {
                            mBrandId = this

                            mBinding.goodsPin.text = objBrand.optNotNull("name")
                            mBinding
                                .goodsPinArrow
                                .apply {
                                    layoutParams.apply {
                                        width = dp2px(15f)
                                        height = dp2px(15f)
                                    }
                                    setImageResource(R.mipmap.icon_arrow_close)
                                }
                        }


                    val objArr = obj.optJSONArray("products") ?: JSONArray()
                    (objArr.length() > 0)
                        .condition {
                            val objProduct = objArr.optJSONObject(0) ?: JSONObject()
                            val objTag = objProduct.optJSONArray("tags") ?: JSONArray()

                            mBinding.apply {
                                goodsLogo.loadImage(objProduct.optNotNull("thumbnail"))
                                goodsSpec.setText(objProduct.optNotNull("spec1"))
                                goodsColor.setText(objProduct.optNotNull("spec2"))
                                goodsPrice.setText(objProduct.optNotNull("price").formatDecimal())
                                goodsReport.text = objProduct.optNotNull("phPrice").formatDecimal()

                                objProduct.optNotNull("marketPrice")
                                    .also {
                                        (it.doubleValue > 0).condition {
                                            goodsMarket.setText(it.formatDecimal())
                                        }
                                    }

                                objProduct.optNotNull("cost")
                                    .also {
                                        (it.doubleValue > 0).condition {
                                            goodsCost.setText(it.formatDecimal())
                                        }
                                    }
                            }

                            // 商品标签
                            productTag {
                                JsonUtil.toList<GoodsTagData>(
                                    objTag.toString(),
                                    GoodsTagData::class.java
                                ).forEach { item ->
                                    mTagList.firstOrNull { item.id == it.id }?.isChecked = true
                                }

                                (mBinding.goodsTag.adapter as SlimAdapter).setDataList(mTagList)
                            }
                        }
                }
            )
    }

}